/*
 * campfire, formerly known as bandcampDirect
 * Copyright (C) 2020 Fynn Godau
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Not affiliated with bandcamp, Incorporated.
 */

package godau.fynn.bandcampdirect.adapter;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import godau.fynn.bandcampdirect.activity.AlbumActivity;
import godau.fynn.bandcampdirect.discover.Database;
import godau.fynn.bandcampdirect.model.Album;
import godau.fynn.bandcampdirect.view.RowView;

import java.util.List;

public class FavoritesAdapter extends RowAdapter<Album> {

    private final Database database;

    public FavoritesAdapter(List<Album> albums, Database database) {
        super(albums);
        this.database = database;
    }

    @Override
    public void onBindViewHolder(RowView rowView, Album a, int position) {
        rowView.bind(a.getTitle(), a.isPaid() || a.isImplicitlyPaid(), RowView.Action.OPEN);

        loadImage(rowView, a, a.getCover());

        rowView.setOnButtonClickListener(view -> {
            Intent intent = new Intent(context, AlbumActivity.class);
            intent.setData(Uri.parse(a.getUrl()));

            intent.putExtra(AlbumActivity.EXTRA_ALBUM, a);

            if (a.getTracks().size() == 1)
                intent.putExtra(AlbumActivity.EXTRA_TRACK, 0);

            context.startActivity(intent);
        });

        rowView.setOnLongClickListener(view -> {
            // Drop album, then recreate
            new Thread(() -> {
                database.drop(a);

                int removePosition = content.indexOf(a);
                content.remove(removePosition);
                new Handler(Looper.getMainLooper()).post(() -> notifyItemRemoved(removePosition));
            }).start();
            return true;
        });

        rowView.setOnItemClickListener(view -> AlbumActivity.play(context, a, 0));

    }

    public void clear() {
        int size = content.size();
        content.clear();
        notifyItemRangeRemoved(0, size);
    }

}
